/**
 * Copyright 2018 人人开源 http://www.gbznt.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package io.gbznt.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.gbznt.common.utils.PageUtils;
import io.gbznt.common.utils.R;
import io.gbznt.common.utils.ShiroUtils;
import io.gbznt.common.validator.ValidatorUtils;
import io.gbznt.modules.sys.entity.SysDictEntity;
import io.gbznt.modules.sys.service.SysDictService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 数据字典
 *
 * @author Mark sunlightcs@gmail.com
 * @since 3.1.0 2018-01-27
 */
@RestController
@RequestMapping("sys/dict")
public class SysDictController {
    @Autowired
    private SysDictService sysDictService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:dict:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = sysDictService.queryPage(params);

        return R.ok().put("page", page);
    }
    
	/**
	 * 列表
	 */
	@RequestMapping("/list2")
//	@RequiresPermissions("sys:dept:list")
	public List<SysDictEntity> list2(@RequestParam Map<String, Object> params){
		List<SysDictEntity> deptList = sysDictService.queryList(params);
		List<Map<String, Object>> dmap = new ArrayList<>();

		/*for (int i = 0; i < deptList.size(); i++) {
            Map<String, Object> nm = new HashMap<>();
            nm.put("id", deptList.get(i).getId());
            nm.put("pId", deptList.get(i).getType());
            nm.put("name", deptList.get(i).getName());
		}*/
		
		return deptList;
	}
    
    /**
     * 查询字典
     */
    @RequestMapping("/finddic")
    //@RequiresPermissions("sys:dict:list")
    public List<SysDictEntity> list(@RequestParam String type){
        List<SysDictEntity> geilist = sysDictService.queryDetpIdList(type);

        return geilist;
    }

    /**
     * 获得字典类型
     */
    @RequestMapping("/findtype/{id}")
    //@RequiresPermissions("sys:dict:list")
    public String findtype(@PathVariable("id") String id){
        //List<SysDictEntity> geilist = sysDictService.queryDetpIdList(type);
    	SysDictEntity sysdict =  sysDictService.getById(id);
    	
    	double sjs = (Math.random()*9+1)*1000;
    	
    	String newtype = sysdict.getType()+"_"+sjs;
    	
    	if(this.name(newtype)>0){
    		sjs = (Math.random()*9+1)*1000;
    	}
    	
        return newtype;
    }
    
    public int name(String newtype) {
    	int s = sysDictService.count(
    			new QueryWrapper<SysDictEntity>()
    			.eq(StringUtils.isNotBlank(newtype), "type", newtype)
    			);
    	return s;
	}

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:dict:info")
    public R info(@PathVariable("id") String id){
        SysDictEntity dict = sysDictService.getById(id);

        return R.ok().put("dict", dict);
    }
    
    /*@RequestMapping("/gettype/{id}")
    @RequiresPermissions("sys:dict:info")
    public R gettype(@PathVariable("id") String id){
        SysDictEntity dict = sysDictService.selectById(id);
        String newtype = "";
        String type = dict.getType();
        String parentid = dict.getParentId();
        int num = 0;
        
        if(StringUtils.isNotBlank(parentid)){
           if("0".equals(parentid)){
        	   newtype = type+"_00";
        	   
        	   if(StringUtils.isNotBlank(type)){
               	num = 1;
               }
           }else{
        	   if(StringUtils.isNotBlank(type)){
                  	num = Integer.parseInt(type.substring(type.indexOf("_"), type.length()))+1;
                  }
        	   newtype = type +"_"+num;
        	   
        	   
           }
        }
        
       // String newtype = type+"_"+01;
        
        
        return R.ok().put("type", newtype);
    }*/
    
    

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:dict:save")
    public R save(@RequestBody SysDictEntity dict){
    	//获取code值
    	String code = sysDictService.getMaxcode(dict.getParentId());
    	if(StringUtils.isNotBlank(code)){
    		dict.setCode((Integer.parseInt(code)+1)+"");
    	}else{
    		dict.setCode("01");
    	}
        //校验类型
    	dict.setName(dict.getValue()); 
        ValidatorUtils.validateEntity(dict);
        
        //字典名称填入字典值

        
        dict.setCreateId(ShiroUtils.getUserId());
        dict.setCreateName(ShiroUtils.getUserName());
        dict.setCreateTime(new Date());
        sysDictService.save(dict);

        Map<String,Object> params = new HashMap<String,Object>();
        params.put("orderNum", dict.getOrderNum()+"");
        List<SysDictEntity> listEx = sysDictService.queryList(params);
        if(listEx.size()>1){
        	// 修改大于等于该排序值对象排序值+1
        	sysDictService.updateOrderNum(dict);
        }
        
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:dict:update")
    public R update(@RequestBody SysDictEntity dict){
        //校验类型
    	dict.setName(dict.getValue()); 
        ValidatorUtils.validateEntity(dict);

        dict.setUpdateId(ShiroUtils.getUserId());
        dict.setUpdateName(ShiroUtils.getUserName());
        dict.setUpdateTime(new Date());
        Boolean reBol = sysDictService.updateById(dict);

        Map<String,Object> params = new HashMap<String,Object>();
        params.put("orderNum", dict.getOrderNum()+"");
        List<SysDictEntity> listEx = sysDictService.queryList(params);
        if(listEx.size()>1){
        	// 修改大于等于该排序值对象排序值+1
        	sysDictService.updateOrderNum(dict);
        }
        
        return reBol?R.ok():R.oldVersion();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:dict:delete")
    public R delete(@RequestBody String[] ids){
    	String failmsg = "";
    	if(ids.length>0){
    		//如果有子集  则不能删除
    		for (int i = 0; i < ids.length; i++) {
    			int nlist =  sysDictService.count(new QueryWrapper<SysDictEntity>()
    					.eq(StringUtils.isNotBlank(ids[i]), "parent_id", ids[i])
    					);
    			if(nlist>0){
    				failmsg = "请先删除子级";
    				return R.error(failmsg);
    			}
    			
    		}
    	}
    	
        sysDictService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * @description 下拉框
     * @author guoqiang
     * @email rd_guoqiang@139.com
     * @date 2019-05-07
     * @params  * @param params
     * @return io.gbznt.common.utils.R
     */
    @RequestMapping("/select")
    public R select(@RequestParam Map<String, Object> params){
    	 List<SysDictEntity> list = sysDictService.queryList(params);
    	 
    	 return R.ok().put("list", list);
    }

    @RequestMapping("/select2")
    public R select2(@RequestParam Map<String, Object> params){
        List<SysDictEntity> list = sysDictService.queryList(params);

        SysDictEntity root = new SysDictEntity();
        root.setId("0");
        root.setName("一级字典");
        root.setValue("一级字典");
        root.setParentId("-1");
        //root.setType("00000");
        root.setOpen(true);
        list.add(root);

        return R.ok().put("list", list);
    }
    
    @RequestMapping("/getMaxOrderNum")
	public R getMaxOrderNum(String parentId){
		return R.ok().put("maxOrderNum", sysDictService.getMaxOrderNum(parentId));
	}
    
}
